package alg.leetcode;

/**
 * 罗马数字转整数 easy
 * @author xujian
 * 2021-07-02 09:45
 **/
public class N52 {
    public static int romanToInt(String s) {
        if (s.length() == 1) {
            return toNumber(s.charAt(0));
        }
        int ret = 0;
        int i = 0;
        while (i<s.length()) {
            Character c = s.charAt(i);
            if (c.equals('I')) {
                if (i == s.length()-1) {
                    ret+=toNumber(c);
                    break;
                }
                Character c1 = s.charAt(i+1);
                if (c1.equals('V') || c1.equals('X')) {
                    ret = ret + (toNumber(c1) - toNumber(c));
                    i++;
                } else {
                    ret+=toNumber(c);
                }
            } else if (c.equals('X')) {
                if (i == s.length()-1) {
                    ret+=toNumber(c);
                    break;
                }
                Character c1 = s.charAt(i+1);
                if (c1.equals('L') || c1.equals('C')) {
                    ret = ret + (toNumber(c1) - toNumber(c));
                    i++;
                } else {
                    ret+=toNumber(c);
                }
            } else if (c.equals('C')) {
                if (i == s.length()-1) {
                    ret+=toNumber(c);
                    break;
                }
                Character c1 = s.charAt(i+1);
                if (c1.equals('D') || c1.equals('M')) {
                    ret = ret + (toNumber(c1) - toNumber(c));
                    i++;
                } else {
                    ret+=toNumber(c);
                }
            } else {
                ret+=toNumber(c);
            }
            i++;
        }
        return ret;
    }

    public static int romanToInt2(String s) {
        if (s == null || s.length()==0) return 0;
        int sum = toNumber(s.charAt(0));
        for (int i = 1; i < s.length(); i++) {
            if (toNumber(s.charAt(i))>toNumber(s.charAt(i-1))) {
                sum +=toNumber(s.charAt(i))-2*toNumber(s.charAt(i-1));
            }else {
                sum += toNumber(s.charAt(i));
            }
        }
        return sum;
    }
    public static int toNumber(Character s) {
        int res = -1;
        switch (s) {
            case 'I':
                return 1;
            case 'V':
                return 5;
            case 'X':
                return 10;
            case 'L':
                return 50;
            case 'C':
                return 100;
            case 'D':
                return 500;
            case 'M':
                return 1000;
        }
        return res;
    }

    public static void main(String[] args) {
        System.out.println(romanToInt("IX"));
    }
}
